package com.tarena.lbs.message.service.impl;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageQuery;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.utils.PageResultBuilder;
import com.tarena.lbs.message.dao.repository.TimingMsgRepository;
import com.tarena.lbs.message.pojo.param.TimingMsgParam;
import com.tarena.lbs.message.pojo.po.TimingMsgTemplatePO;
import com.tarena.lbs.message.pojo.vo.TimingMsgTemplateVO;
import com.tarena.lbs.message.service.TimingMsgService;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TimingMsgServiceImpl implements TimingMsgService {
    private final TimingMsgRepository timingMsgRepository;
    @DubboReference
    private UserApi userApi;
    @Override
    public PageResult<TimingMsgTemplateVO> selectAll(BasePageQuery query) throws BusinessException{
        UserPrinciple user = AuthenticationContextUtils.get();
        Asserts.isTrue(user == null, new BusinessException("-2", "用户身份校验失败"));
        AdminDto adminDto = userApi.getAdminById(user.getId());
        List<TimingMsgTemplatePO> timingMsgList = timingMsgRepository.selectAll();
        List<TimingMsgTemplateVO> result = timingMsgList.stream().filter(
                item -> item.getBusinessId().equals(adminDto.getBusinessId())
        ).map(item -> {
            TimingMsgTemplateVO vo = new TimingMsgTemplateVO();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateAt(item.getCreateTime());
            return vo;
        }).toList();
        return PageResultBuilder.build(result,query);
    }
    @Override
    public void saveTemplate(TimingMsgParam param) throws BusinessException {
        UserPrinciple user = AuthenticationContextUtils.get();
        Asserts.isTrue(user == null, new BusinessException("-2", "用户身份校验失败"));
        AdminDto adminDto = userApi.getAdminById(user.getId());
        TimingMsgTemplatePO po = new TimingMsgTemplatePO();
        BeanUtils.copyProperties(param, po);
        if(po.getId() == null){
            po.setBusinessId(adminDto.getBusinessId());
            po.setCreateTime(new Date());
            po.setUpdateTime(new Date());
            timingMsgRepository.add(po);
        }else {
            po.setUpdateTime(new Date());
            timingMsgRepository.update(po);
        }
    }
    @Override
    public void deleteTemplate(Integer id) throws BusinessException {
        timingMsgRepository.delete(id);
    }
}
